package com.woniuxy.demo.epai.controller;


import com.woniuxy.demo.epai.common.Result;
import com.woniuxy.demo.epai.controller.component.ControllerBase;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController

public class UploadController extends ControllerBase {

    private static final String UPLOAD_DIR="\\\\192.168.50.27\\webserve\\";

    private static  final String STATIC_SERVER_ADDRESS="http://192.168.50.27:8000/";

    @PostMapping("upload")
    public Result upload(@RequestParam MultipartFile file) throws IOException {
        //获取上传文件的文件名
        String originalFilename = file.getOriginalFilename();
        //生成文件名
        String fileName = generate(originalFilename);
        //转存到设置的文件夹位置
        File file1 = new File(UPLOAD_DIR + fileName);

        file.transferTo(file1);

        //设置网络路径
        String webPath = STATIC_SERVER_ADDRESS+fileName;
        return Result.success(webPath);
    }

    /**
     * 生成文件名
     * @param originalFilename
     * @return
     */
    private String generate(String originalFilename) {
        //生成时间戳
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format = simpleDateFormat.format(new Date());
        //生成随机数
        int nextInt = new Random().nextInt(10000);
        //拼接文件名
        return format+nextInt+originalFilename;

    }
}
